package com.citicpub_cloud.restfull.utils;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

/**
 * Created by dlm on 2016/4/17.
 */
public class JsonDateValueProcessor implements JsonValueProcessor {

    private static Logger log = LoggerFactory.getLogger(JsonDateValueProcessor.class);
    private String datePattern = "yyyy-MM-dd HH:mm:ss";


    public JsonDateValueProcessor() {
        super();
    }

    public JsonDateValueProcessor(String format) {
        super();
        this.datePattern = format;
    }


    @Override
    public Object processArrayValue(Object value, JsonConfig jsonConfig) {
        return process(value);
    }


    @Override
    public Object processObjectValue(String key, Object value,JsonConfig jsonConfig) {
        return process(value);
    }


    private Object process(Object value) {
        try {
            if (value instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
                return sdf.format((Date) value);
            }
            return value == null ? "" : value.toString();
        } catch (Exception e) {
            log.error("日期转json出错",e);
            return "";
        }
    }


    public String getDatePattern() {
        return datePattern;
    }


    public void setDatePattern(String pDatePattern) {
        datePattern = pDatePattern;
    }

 }
